'nodejs';

const StyleMenu = require('../modules/__style_menu__');
const { dp2px } = require('../modules/__util__');
const MenuWindow = require('../windows/menu_window');


class HorizontalMenu extends StyleMenu {

    /**
     * 水平菜单样式
     * @param {MenuWindow} window 
     */
    constructor(window) {
        super(window);
        init(this);
    }

    updateMenuPosition() {
        this.positions = createItemViewPosition(this);
    }

    updateMenuWindow() {
        let window = this.window;
        if (!window.isInit) return null;
        let ivs = this.fm.getItemViews();
        let len = ivs.length;
        let size = dp2px(this.config.all_item_size);
        let gap = dp2px(this.config.menu_item_gap);
        window.setSize((size + gap) * (len + 1), -2);
        //更新悬浮窗位置
        try {
            let x = this.fm.logoWindow.getX();
            let y = this.fm.logoWindow.getY();
            if (!this.config.isLeftMargin)
                x -= (size + gap) * (len + 1) - size;
            window.setPosition(x, y);
        } catch (error) {
            console.error('更新菜单悬浮窗位置失败', error);
        }
    }

    updateMenuAnimation(f) {
        let e = Number(!this.config.isLeftMargin);
        this.fm.getItemViews().forEach((iv, i) => {
            iv.setTranslationX(this.positions[i].x[e] * f);
        });
    }
}

/** @param {HorizontalMenu} scope */
function init(scope) {
    scope.updateMenuPosition();
    if (scope.window.isInit) {
        scope.updateMenuWindow();
    }
}

/**
 * 创建菜单ItemViews坐标
 * @param {HorizontalMenu} scope 
 */
function createItemViewPosition(scope) {
    let items = scope.fm.getItemViews();
    let len = items.length;
    let size = dp2px(scope.config.all_item_size);
    let gap = dp2px(scope.config.menu_item_gap);
    let w = size + gap;
    return items.map((iv, i, arr) => {
        return { x: [w * (i + 1), -(w * (len - i))] }
    });
}

module.exports = HorizontalMenu;
